package com.sure0000.basicKafka.example;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Properties;

/**
 * @program: demo
 * @description:
 * @author: xuyouchang@supcon.com
 * @create: 2019-12-03 14:28
 **/
public class KafkaConsumerDemo {

    private static final Logger logger = LoggerFactory.getLogger(KafkaConsumerDemo.class);

    public void avroComsumer(String bootstrap, String group, String topic, String schemaUrl) {
        KafkaConsumer<byte[], byte[]> consumer = new KafkaConsumer<>(getProps(bootstrap, group, schemaUrl));
        consumer.subscribe(Collections.singletonList(topic));
        while (true) {
            ConsumerRecords<byte[], byte[]> records = consumer.poll(100);
            for (ConsumerRecord<byte[], byte[]> record : records) {
                String avroRecord = new String(record.value());
                logger.info("consumer record: {}",avroRecord);
            }
        }
    }

    public void jsonComsumer(String bootstrap, String group, String topic) {
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(getProps(bootstrap, group, null));
        consumer.subscribe(Collections.singletonList(topic));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(10000);
            for (ConsumerRecord<String, String> record : records) {
                logger.info("consumer record: {}",record.value());
            }
        }
    }

    private Properties getProps(String bootstrap, String group, String schemaUrl) {
        Properties props=new Properties();

        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrap);
        props.put(ConsumerConfig.GROUP_ID_CONFIG,group);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class);
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");
//        props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaUrl);
//        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
//        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,KafkaAvroDeserializer.class);
        return props;
    }
}
